﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using YmtAuth.Domain;
using YmtAuth.Domain.Repository;
using YmtSystem.CrossCutting;
using YmtAuth.Dto;

namespace YmtAuth.Repository.MySQL
{
    public class AuthSafeVerifyLogRepository : MySQLRepository<SafeVerifyLogEntity>, IAuthSafeVerifyLogRepository
    {
        public AuthSafeVerifyLogRepository()
            : base(ConfigurationManager.AppSettings["SafeVerifyLog"], "authsafeverifylog")
        {

        }

        /// <summary>
        /// 获取最近X天的用户（登录名）登录风控日志（pc, app）
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="loginId"></param>
        /// <param name="mobile"></param>
        /// <param name="email"></param>
        /// <param name="dayCount"></param>
        /// <returns></returns>
        public ResponseData<List<SafeVerifyLogEntity>> GetLastLoginSafeVerifyLog(int userId, string loginId, string mobile, string email, int dayCount)
        {
            ResponseData<List<SafeVerifyLogEntity>> response = null;
            List<SafeVerifyLogEntity> loginSafeVerifyLogList = new List<SafeVerifyLogEntity>();
            try
            {
                DateTime queryDate = DateTime.Now.AddDays(-dayCount);

                StringBuilder selectSQL = new StringBuilder("SELECT StrategyType, AppSource, UserId, LoginId, LoginIp, DeviceId, ClientId, AuthType, ResponseCode, ResponseDesc, IpArea, LastAuthTime, ExpiredTime, CreateTime FROM authsafeverifylog WHERE CreateTime > @queryDate AND ( LoginId = @LoginId ");
                
                var par = new DynamicParameters();
                par.Add("@loginId", loginId, DbType.String);
                par.Add("@queryDate", queryDate, DbType.DateTime);

                if (userId > 0)
                {
                    selectSQL.AppendFormat(" OR UserId = @userId");
                    par.Add("@userId", userId, DbType.Int32);
                };

                if (!string.IsNullOrEmpty(mobile))
                {
                    selectSQL.AppendFormat(" OR LoginId = @mobile");
                    par.Add("@mobile", mobile, DbType.String);
                }

                if (!string.IsNullOrEmpty(email))
                {
                    selectSQL.AppendFormat(" OR LoginId = @email");
                    par.Add("@email", email, DbType.String);
                }

                selectSQL.Append(" )");

                using (var conn = new MySqlConnection(ConfigurationManager.AppSettings["SafeVerifyLog"]))
                {
                    var loglist = conn.Query<SafeVerifyLogEntity>(selectSQL.ToString(), par, commandType: CommandType.Text);
                    if (loglist != null)
                        loginSafeVerifyLogList = loglist.ToList();
                }

                response = ResponseData<List<SafeVerifyLogEntity>>.CreateSuccess(loginSafeVerifyLogList, "Success");
            }
            catch (Exception ex)
            {
                YmatouLoggingService.Error("获取风控日志出现异常, " + ex.Message, ex);

                response = ResponseData<List<SafeVerifyLogEntity>>.CreateFail(loginSafeVerifyLogList, "400", "获取风控日志出现异常, " + ex.Message);
            }

            return response;
        }
    }
}
